package com.qiqidream.admin.common.response;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.IOUtils;
import com.qiqidream.admin.common.config.EncodeConfig;
import com.qiqidream.admin.common.utils.EncodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.List;

/**
 * @author QiQiDream
 * @since 2020/1/7 10:54
 */
@ControllerAdvice
@Slf4j
public class RequestResultHandlerAdvice  implements RequestBodyAdvice {

    @Resource
    EncodeConfig encodeConfig;

    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return encodeConfig.getEnabled();
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
        return new HttpInputMessage() {
            @Override
            public InputStream getBody() {
                String bodyStr = null;
                try {
                    bodyStr = IOUtils.toString(httpInputMessage.getBody());
                    JSONObject jsonObject = JSONObject.parseObject(bodyStr);
                    bodyStr = EncodeUtil.decrypt(jsonObject.getString("request"));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                return StringUtils.isEmpty(bodyStr)?null:new ByteArrayInputStream(bodyStr.getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                return httpInputMessage.getHeaders();
            }
        };
    }

    @Override
    public Object afterBodyRead(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {

        return o;
    }

    @Override
    public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return o;
    }
}
